<template>
  <div class="keyboard_container">
    <h2 class="title">键盘操作</h2>
    <el-divider />
    <div class="actions">
      <el-button type="primary" @click="insertKey">添加按键</el-button>
      <el-button type="danger" @click="clearKey">清空按键</el-button>
      <div class="message_show">{{ message }}</div>
    </div>

    <div class="key_list">
      <el-table :data="config.list" style="width: 100%" class="key_table">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column label="按键">
          <template #default="scope">
            <el-button @click="listenKey(scope.$index)" class="key_button">
              {{ getKeyText(scope.row) }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="按压时间(ms)">
          <template #default="scope">
            <el-input v-model="scope.row.duration"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="执行间隔(ms)">
          <template #default="scope">
            <el-input v-model="scope.row.interval"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="danger" circle :icon="Close" @click="removeKey(scope.$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 停止条件设置 -->
    <div class="stop_config">
      <stop-condition v-model="stopCondition" class="stop_condition" @update="updateStop" />
      <el-button
        @keydown.space.prevent
        @keydown.enter.prevent
        class="action_button"
        :type="isRunning ? 'danger' : 'primary'"
        :icon="isRunning ? VideoPause : VideoPlay"
        @click="toggleExecutor"
      >
        {{ isRunning ? '紧急停止' : '开始运行' }}({{ hotkeyLabel }})
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, onMounted, onUnmounted } from 'vue'
import { Close, VideoPlay, VideoPause } from '@element-plus/icons-vue'
import request from '@/utils/request.js'

import StopCondition from '@/components/stopCondition.vue'

const stopCondition = ref({
  maxExecutions: -1,
  maxTime: -1,
})

const config = ref({
  list: [],
  maxExecutions: -1,
  maxTime: -1,
})
const listenning = ref(false)
const isRunning = ref(false)
const message = ref('执行器暂未启动')
var socket = null

const hotkeyLabel = ref('F10')

onMounted(async () => {
  const res = await request.get(`/setting/name/keyboard.toggle`)
  hotkeyLabel.value = res.data.key
})

const getKeyText = (keyItem) => {
  let prefix = ''
  if (keyItem.hasShift) prefix += 'Shift+'
  if (keyItem.hasCtrl) prefix += 'Ctrl+'
  if (keyItem.hasAlt) prefix += 'Alt+'
  if (keyItem.hasWin) prefix += 'Win+'
  return prefix + keyCodeToName(keyItem.keyCode)
}

const keyCodeToName = (code) => {
  const map = {
    null: '未知按键',
    SPACE: 'Space',
    CONTROL: 'Ctrl',
    SHIFT: 'Shift',
    ALT: 'Alt',
    WIN: 'Win',
    // 添加其他按键映射...
  }
  return map[code] || code
}

const updateStop = async () => {
  const res = await request.postJson('/keyboard/stop/condition', stopCondition.value)
  config.value = res.data.config
}

const insertKey = async () => {
  const res = await request.post('/keyboard/insert')
  config.value = res.data.config
}

const removeKey = async (index) => {
  const res = await request.post(`/keyboard/remove?index=${index}`)
  config.value = res.data.config
}

const clearKey = async () => {
  const res = await request.post('/keyboard/clear')
  config.value = res.data.config
}

const toggleExecutor = async () => {
  request.post('/keyboard/toggle')
}

const listenKey = async (index) => {
  if (listenning.value) return // 已经在监听按键了
  listenning.value = true // 设置状态量
  request.post(`/keyboard/listener?index=${index}`)
}

const webSocketManager = inject('webSocketManager') // 通过inject获取全局实例
// WebSocket订阅回调
const handleExecutorStatus = (status) => {
  isRunning.value = status.state === 'RUNNING' || status.state === 'COUNTDOWN'
  message.value = status.messages[status.messages.length - 1].message
}

const handleKeyboardConfig = (status) => {
  config.value = status
  listenning.value = false
}
// 页面挂载时：订阅+绑定接口
onMounted(async () => {
  // 订阅WebSocket频道
  webSocketManager.subscribe('/topic/keyboard-executor', handleExecutorStatus)
  webSocketManager.subscribe('/topic/keyboard-config', handleKeyboardConfig)

  // 调用绑定接口（假设需要）
  await request.post('/keyboard/bind')
})

// 页面卸载时：取消订阅+解绑接口
onUnmounted(async () => {
  // 取消WebSocket订阅
  webSocketManager.unsubscribe('/topic/keyboard-executor')
  webSocketManager.unsubscribe('/topic/keyboard-config')

  // 调用解绑接口（假设需要）
  await request.post('/keyboard/unbind')
})
</script>

<style lang="less" scoped>
@import url('../assets/main.less');

.keyboard_container {
  padding: 0px 24px;
  border-radius: 12px;

  .title {
    color: var(--el-text-color-primary);
    font-size: 1.5em;
    margin-bottom: 1em;
    position: relative;
    margin-top: 10px;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 0;
      width: 50px;
      height: 3px;
      background: @primary-color;
    }
  }

  .actions {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;

    .control-group {
      display: flex;
      gap: 10px;
      border-left: 2px solid #eee;
      padding-left: 10px;
    }

    .message_show {
      background-color: @bg-color;
      line-height: 40px;
      height: 40px;
      width: 50%;
      margin-left: 60px;
      text-align: center;
      border-radius: 10px;
    }
  }

  .key_list {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;
    .key_table {
      height: calc(100vh - 300px);
    }

    .key_button {
      width: 100%;
    }
  }

  .stop_config {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;

    .stop_condition {
      width: 400px;
    }

    .action_button {
      height: 40px;
    }
  }
}
</style>
